package com.dubbo.protocol.http;

import com.dubbo.protocol.bean.Invocation;
import com.dubbo.register.RegisterFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Method;
import java.util.Map;

public class HttpHandler
{
    public void handler(HttpServletRequest req, HttpServletResponse resp)
    {
        try
        {
//            ObjectInputStream ois = new ObjectInputStream(req.getInputStream());
//            Invocation invocation = (Invocation) ois.readObject();
//            System.out.println("httpHandler get invocation: " + invocation);
//
//            Map<String, Object> localRegister = RegisterFactory.get(RegisterFactory.LOCAL);
//            Class clazz = (Class) localRegister.get(invocation.getInterfaceName());
//
//            Method method = clazz.getMethod(invocation.getMethodName(), invocation.getParamsClass());
//
//            Object result = method.invoke(clazz.newInstance(), invocation.getParamsValue());
//
//            ObjectOutputStream oos = new ObjectOutputStream(resp.getOutputStream());
//            oos.writeObject(result);
            HttpHandler.mainHandler(req.getInputStream(), resp.getOutputStream());
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

    }

    public static void mainHandler(InputStream inputStream, OutputStream outputStream)
    {
        ObjectInputStream ois = null;
        try
        {
            ois = new ObjectInputStream(inputStream);

            Invocation invocation = (Invocation) ois.readObject();
            System.out.println("httpHandler get invocation: " + invocation);

            Map<String, Object> localRegister = RegisterFactory.get(RegisterFactory.LOCAL);
            Class clazz = (Class) localRegister.get(invocation.getInterfaceName());

            Method method = clazz.getMethod(invocation.getMethodName(), invocation.getParamsClass());
            Object result = method.invoke(clazz.newInstance(), invocation.getParamsValue());
            ObjectOutputStream oos = new ObjectOutputStream(outputStream);
            oos.writeObject(result);

        } catch (Exception e)
        {
            e.printStackTrace();
        }

    }


}
